package by.bsu.fpmi.bbtp.authentication;

import by.bsu.fpmi.bbtp.dao.UserDAO;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jws.WebService;
import java.util.*;

@WebService(endpointInterface = "by.bsu.fpmi.bbtp.authentication.LoginController")
public class LoginControllerImpl implements LoginController {
    
    private static final long TIMEOUT = 1000 * 60 * 10; // 10 minutes
    private Map<String, Date> lastVisitedTime;
    private Map<String, Role> roles;
    
    @Autowired
    private UserDAO userDao;
    
    public LoginControllerImpl() {
        lastVisitedTime = new HashMap<String, Date>();
        roles = new WeakHashMap<String, Role>();
    }

    @Override
    public LoginResponse login(String username, String password) {
        LoginResponse response = new LoginResponse();
        User user = userDao.findUserByName(username);
        if (user != null && user.getPassword().equals(password)) {
            String sessionId = generateSessionId();
            lastVisitedTime.put(sessionId, new Date());
            roles.put(sessionId, user.getRole());
            response.setResult(LoginResponse.Result.SUCCESS);
            response.setRole(user.getRole());
            response.setSessionId(sessionId);
        } else {
            response.setResult(LoginResponse.Result.FAIL);
        }
        return response;
    }
    
    @Override
    public boolean isAuthenticatedAs(String sessionId, Role role) {
        Date lastVisited = lastVisitedTime.get(sessionId);
        if (roles.get(sessionId) == role && lastVisited != null && !isExpired(lastVisited)) {
            lastVisitedTime.put(sessionId, new Date());
            return true;
        } else {
            return false;
        }
    }
    
    private String generateSessionId() {
        return UUID.randomUUID().toString();
    }
    
    private boolean isExpired(Date date) {
        return new Date().getTime() - date.getTime() > TIMEOUT;
    }
}